package com.hfjyz.exam.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import com.hfjyz.exam.command.ExamSearchCommand;
import com.hfjyz.exam.model.ExamInfo;
import com.hfjyz.exam.util.ValidatorUtil;

public class ExamInfoDaoImpl extends BaseDaoImpl<ExamInfo, Integer> implements
		ExamInfoDao {

	protected ExamInfoDaoImpl() {
		super(ExamInfo.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public ExamInfo getByUid(Integer uid, Integer pid) throws Exception {
		List<ExamInfo> es = hibernateTemplate
				.find(" from ExamInfo as e where e.userInfo.id = ? and e.paper.id = ? ",
						new Object[] { uid, pid });
		if (es == null || es.isEmpty()) {
			return null;
		}
		return es.get(0);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ExamInfo> findByUid(Integer uid) throws Exception {
		return hibernateTemplate.find(
				" from ExamInfo as e where e.userInfo.id = ?", uid);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ExamInfo> find(ExamSearchCommand cmd) throws Exception {
		DetachedCriteria dc = DetachedCriteria.forClass(ExamInfo.class);
		dc.createAlias("userInfo", "u").createAlias("paper", "p");
		if (!ValidatorUtil.isEmpty(cmd.getUname())) {
			dc.add(Restrictions.like("u.name", cmd.getUname(),
					MatchMode.ANYWHERE));
		}
		if (!ValidatorUtil.isEmpty(cmd.getIdCardNo())) {
			dc.add(Restrictions.eq("u.idCardNo", cmd.getIdCardNo()));
		}
		if (cmd.getUid() != null) {
			dc.add(Restrictions.eq("u.id", cmd.getUid()));
		}
		if (cmd.getPid() != null) {
			dc.add(Restrictions.eq("p.id", cmd.getPid()));
		}
		List<ExamInfo> es = hibernateTemplate.findByCriteria(dc);
		return es;
	}

}
